package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Override
    public List<Category> findAll() {
        List<Category> categoryList = categoryMapper.findAll();
        return categoryList;
    }

    @Override
    public void save(Category category) {
        //补齐参数
        category.setId(IdUtil.getSnowflake(1,1).nextId());
//        category.setCreateTime(new Date());
//        category.setUpdateTime(new Date());
        //先写死
//        category.setCreateUser(1l);
//        category.setUpdateUser(1l);
        categoryMapper.save(category);
    }

    //更新
    @Override
    public void update(Category category) {
        //修改更新信息
//        category.setUpdateTime(new Date());
//        category.setUpdateUser(1l);

        //调用方法
        categoryMapper.updateById(category);
    }

    //根据id删除
    @Override
    public ResultInfo deleteById(long id) {
        //1.先判断该菜品里是否包含菜名
        int count1 = categoryMapper.countDishById(id);
        int i=1/0;
        //1.1包含的话，就返回  该菜系包含菜品，不可删除
        if (count1 > 0){
            throw new CustomException("该菜系包含菜品，不可删除");
        }
        //2.判断该套餐里是否包含菜名
        int count2 = categoryMapper.countSetmealById(id);
        //2.1包含的话，就返回  该菜系包含菜品，不可删除
        if (count2 > 0){
            throw new CustomException("该菜系包含菜品，不可删除");
        }
        //3.都不包含的话，就直接删除
        categoryMapper.deleteById(id);
        return ResultInfo.success(null);
    }

    @Override
    public List<Category> findList(Integer type) {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getType,type);
        return categoryMapper.selectList(wrapper);
    }
}
